/**
 * Reads nodeRef and data object from URL and modifies the properties of related
 * file.
 */
function main() {
	// parse json object
	var jsonobj = args.obj;
	var obj = eval('(' + jsonobj + ')');
	// find referenced scriptNode
	var nodeRef = args.node;
	// var nodeRef = param.substring(1, param.length - 1);
	var file = search.findNode(nodeRef);

	applyMetadata(file, obj);
}

/**
 * Applies the metadata defined in obj to the file
 * 
 * @param file
 * @param obj
 */
function applyMetadata(file, obj) {
	for (prop in obj) {
		// add an exception for date prop (date must be calculated in server
		// side)
		if (prop == "{http://www.alfresco.org/model/recordsmanagement/1.0}publicationDate") {
			file.properties[prop] = getDate();
		} else {
			if(obj[prop]=="null"){
				file.properties[prop] = null;
			}else{
				file.properties[prop] = obj[prop];
			}
		}
	}

	// apply changes
	file.save();

	// if deep is enabled, apply data to children
	if (file.isContainer && args.deep == "true") {
		for ( var i = 0; i < file.children.length; i++) {
			applyMetadata(file.children[i], obj);
		}
	}
}

function getDate() {
	var date = new Date();
	var dateStr = date.getFullYear() + "-" + fixSize(2, date.getMonth() + 1)
			+ "-" + fixSize(2, date.getDate()) + "T"
			+ fixSize(2, date.getHours()) + ":" + fixSize(2, date.getMinutes())
			+ ":" + fixSize(2, date.getSeconds()) + "."
			+ fixSize(3, date.getMilliseconds()) + "+02:00";
	return dateStr;
}

/**
 * Alfresco d:date type restricts date format as : YYYY-MM-DDThh:mm:ss.mmm+02:00
 * 
 * @param preferredSize
 *            required field size (such as 2 for MM, 4 for YYYY)
 * @param prop
 *            current date value (such as MM=1, YYYY=2010)
 * @return current date value in a fixed size
 */
function fixSize(preferredSize, prop) {
	var newProp = prop;
	if (prop.toString().length < preferredSize) {
		for ( var i = 0; i < preferredSize - prop.toString().length; i++) {
			// apply zeros to the head of the prop
			newProp = "0" + newProp;
		}
	}
	return newProp;
}

main();